package com.yupi.yupao.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.config.JWTConfig;
import com.yupi.yupao.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Peter
 * @Date: 2024-09-17-21:20
 * @Description: Pe
 */
@Component
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Resource
    private JWTConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 获取请求头，header值为Authorization，承载token
        String token = request.getHeader(jwtConfig.getHeader());
        try{
            DecodedJWT jwtToken = jwtConfig.decodedJWT(token);
            Long userId= Long.valueOf(jwtToken.getSubject());
            BaseContext.setCurrentId(userId);//存userid
            return true;
        }catch (Exception e){
            response.setStatus(401);
            throw new BusinessException(ErrorCode.NOT_LOGIN);

        }
        //token不存在
//        if (token == null || token.equals("")) {
//            log.info("传入token为空");
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token为空!");
//            return false;
//        }
//        //验证token
//        String sub = jwtConfig.validateToken(token);
//        if (sub == null || sub.equals("")){
//            log.info("token验证失败");
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token验证失败!");
//            return false;
//        }
        //如果token存在并且验证成功（token未过期）
        //token 解密获取userid


        //更新token有效时间 (如果需要更新其实就是产生一个新的token)
//        if (jwtConfig.isNeedUpdate(token)){
//            String newToken = jwtConfig.createToken(sub);
//            response.setHeader(jwtConfig.getHeader(),newToken);
//        }

    }

}
